package org.edu.modules.oa.controller;


import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectResult;
import com.rabbitmq.client.Return;
import groovy.util.logging.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.edu.common.api.vo.Result;
import org.edu.common.aspect.annotation.AutoLog;
import org.edu.common.system.vo.LoginUser;
import org.edu.common.util.RedisUtil;
import org.edu.modules.oa.entity.VeFileFilesEntity;
import org.edu.modules.oa.entity.VeOaYinzhangEntity;
import org.edu.modules.oa.service.IVeOaYinzhangService;
import org.edu.modules.oa.vo.VeOaTongxunluVo;
import org.edu.modules.oa.vo.VeOaYinzhangVo;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

@Api(tags="印章管理-公共印章")
@RestController
@RequestMapping("/oa/VeOaCommonYinzhang")
@Slf4j
public class VeOaCommonYinzhangController {

    @Autowired
    private RedisUtil redisUtil; // redis服务类
    @Resource
    private IVeOaYinzhangService veOaYinzhangService;
    @Resource
    private OSS ossClient;


    //增加印章信息，对应的图片
    @AutoLog(value = "印章管理-公共印章")
    @ApiOperation(value="增加公共印章", notes="印章管理-增加公共印章")
    @PostMapping(value = "/addYinzhang")
    public Result<?> addYinzhang(MultipartFile file, VeOaYinzhangEntity veOaYinzhangEntity){
        System.out.println(veOaYinzhangEntity);
        //重复校验
        VeOaYinzhangEntity yinzhangEntity = veOaYinzhangService.checkByName(veOaYinzhangEntity);
        if (yinzhangEntity != null){
            return Result.error(500,"印章名称重复，请重新输入");
        }

        //创建文件类
        VeFileFilesEntity veFileFilesEntity = null;
        String fileName = null;
        String suffixName = null;
        if(file != null){
            //myFile为MultipartFile类型
//            CommonsMultipartFile cf= (CommonsMultipartFile)file;
//            DiskFileItem fi = (DiskFileItem)cf.getFileItem();
//            File document = fi.getStoreLocation();
            //把MultipartFile文件流转换成文件
            File document = null;
            //获取文件名
            fileName = file.getOriginalFilename();
            //用点来切割获取文件类型注意//.需要加双斜杠正则表达式
            String[] arr = fileName.split("\\.");
            //获取文件后缀名
            suffixName = arr[arr.length-1];
            if(!suffixName.equalsIgnoreCase("png") && !suffixName.equalsIgnoreCase("jpg")
                    && !suffixName.equalsIgnoreCase("gif") && !suffixName.equalsIgnoreCase("JPEG")
                    && !suffixName.equalsIgnoreCase("BMP") && !suffixName.equalsIgnoreCase("svg")
                    && !suffixName.equalsIgnoreCase("psd") && !suffixName.equalsIgnoreCase("pdd")
            ){
                return Result.error(400,"不支持图片以外的文件不能上传");
            }
            try {
                String originalFilename = file.getOriginalFilename();
                String[] filename = originalFilename.split("\\.");
                if (filename[0].length()>=3){
                    document=File.createTempFile(filename[0], filename[1]);
                }else {
                    document=File.createTempFile(filename[0]+"(1)", filename[1]);
                }
                file.transferTo(document);
                document.deleteOnExit();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //获取文件长度
            Long size = file.getSize();
            //获取唯一的文件名称
            String docName = UUID.randomUUID().toString()+"."+suffixName;
            //上传文件到指定的存储空间  第一个参数 bucketName  第二个参数 OSS存储路径  第三个参数 要上传的文件
            PutObjectResult result = ossClient.putObject("digital-school-xx0422","school-demo/"+docName,document);
            //文件下载地址
            String path = "https://digital-school-xx0422.oss-cn-shenzhen.aliyuncs.com/school-demo/"+docName;
            System.out.println("-----------文件下载地址-------"+path);
            veFileFilesEntity = new VeFileFilesEntity();
            //当前插入的时间
            Long time = System.currentTimeMillis()/1000;
            veFileFilesEntity.setSourceFile(path);
            veFileFilesEntity.setName(fileName);
            veFileFilesEntity.setExt(suffixName);
            veFileFilesEntity.setCreateTime(time);
            veFileFilesEntity.setSize(size);
        }

        // 获取redis存的用户值
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //设置印章添加的值
        veOaYinzhangEntity.setCreateUserId(user.getId());
        veOaYinzhangEntity.setCreateUserName(user.getRealname());
        veOaYinzhangEntity.setIsDeleted(0);
        veOaYinzhangEntity.setTerminalId(1);
        veOaYinzhangEntity.setYinZhangLeiBie("公共印章");
        //添加
        Integer res = veOaYinzhangService.addYinzhang(veOaYinzhangEntity,veFileFilesEntity);
        if (res == 0){
            return Result.error(500,"添加失败");
        }
        return Result.OK();
    }


    //修改印章信息 有图片时也要修改
    @AutoLog(value = "印章管理-公共印章")
    @ApiOperation(value="修改公共印章", notes="印章管理-修改公共印章")
    @PostMapping(value = "/updateYinzhang")
    public Result<?> updateYinzhang(MultipartFile file, VeOaYinzhangEntity veOaYinzhangEntity) throws ParseException {
        //重复校验 印章名称
        VeOaYinzhangEntity chongfuEntity = veOaYinzhangService.checkByName(veOaYinzhangEntity);
        if (chongfuEntity != null){
            return Result.error(500,"印章名称和其它印章重复");
        }
        //创建文件类
        VeFileFilesEntity veFileFilesEntity = null;
        String fileName = null;
        String suffixName = null;
        //当文件不为空时，上传并修改文件
        if(file != null){
            File document = null;
            //获取文件名
            fileName = file.getOriginalFilename();
            //用点来切割获取文件类型注意//.需要加双斜杠正则表达式
            String[] arr = fileName.split("\\.");
            //获取文件后缀名
            suffixName = arr[arr.length-1];
            if(!suffixName.equalsIgnoreCase("png") && !suffixName.equalsIgnoreCase("jpg")
                    && !suffixName.equalsIgnoreCase("gif") && !suffixName.equalsIgnoreCase("JPEG")
                    && !suffixName.equalsIgnoreCase("BMP") && !suffixName.equalsIgnoreCase("svg")
                    && !suffixName.equalsIgnoreCase("psd") && !suffixName.equalsIgnoreCase("pdd")
            ){
                return Result.error(400,"不支持图片以外的文件不能上传");
            }

            try {
                String originalFilename = file.getOriginalFilename();
                String[] filename = originalFilename.split("\\.");
                document=File.createTempFile(filename[0], filename[1]);
                file.transferTo(document);
                document.deleteOnExit();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //获取文件长度
            Long size = file.getSize();
            //获取唯一的文件名称
            String docName = UUID.randomUUID().toString()+"."+suffixName;
            //上传文件到指定的存储空间  第一个参数 bucketName  第二个参数 OSS存储路径  第三个参数 要上传的文件
            PutObjectResult result = ossClient.putObject("digital-school-xx0422","school-demo/"+docName,document);
            //文件下载地址
            String path = "https://digital-school-xx0422.oss-cn-shenzhen.aliyuncs.com/school-demo/"+docName;
            veFileFilesEntity = new VeFileFilesEntity();
            //当前插入的时间
            Long time = System.currentTimeMillis()/1000;
            veFileFilesEntity.setSourceFile(path);
            veFileFilesEntity.setName(fileName);
            veFileFilesEntity.setExt(suffixName);
            veFileFilesEntity.setCreateTime(time);
            veFileFilesEntity.setSize(size);

        }
        // 获取redis存的用户值
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //修改印章
        Integer result = null;
        try {
            result = veOaYinzhangService.updateYinzhang(veOaYinzhangEntity,veFileFilesEntity);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(500,"文件或数据有问题不能上传修改");
        }

        return Result.OK(result);
    }



    //查询印章名称
    @AutoLog(value = "印章管理-查询印章名称")
    @ApiOperation(value = "查询印章名称", notes = "印章管理-查询印章名称")
    @PostMapping(value = "/searchYinzhangName")
    public Result<?> searchYinzhangName(){
        HashMap<String,Object> map = veOaYinzhangService.selectYinzhangName();
        return Result.OK(map);
    }


    //查询 显示表格
    @AutoLog(value = "印章管理-显示表格")
    @ApiOperation(value = "查看公章表格", notes = "印章管理-显示表格")
    @PostMapping(value = "/searchTable")
    public Result<?> searchTable(Integer currentPage,Integer pageSize,VeOaYinzhangEntity veOaYinzhangEntity){
        veOaYinzhangEntity.setYinZhangLeiBie("公共印章");
        HashMap<String,Object> map = veOaYinzhangService.showTable(veOaYinzhangEntity,currentPage,pageSize);
        return Result.OK(map);
    }

    //删除单/多条
    @AutoLog(value = "印章管理-删除多条公共印章数据")
    @ApiOperation(value = "删除多条公共印章数据", notes = "印章管理-删除多条公共印章数据")
    @GetMapping(value = "/deleteAll")
    public Result<?> deleteAll(@RequestParam List<String> ids){
        System.out.println("数组"+ids);
        List<Long> list = new ArrayList<>();
        for (int i=0;i<ids.size();i++){
            System.out.println(ids.get(i));
            list.add(Long.parseLong(ids.get(i)));
        }
        int res = veOaYinzhangService.deleteYinzhang(list);
        if (res == 0){
            return  Result.error(500,"删除失败");
        }
        return Result.OK("删除成功");
    }

    //查询印章对应的文件详情
    @AutoLog(value = "印章管理-查询印章对应的文件详情")
    @ApiOperation(value = "查询印章对应的文件详情", notes = "印章管理-查询印章对应的文件详情")
    @PostMapping(value = "/searchItsFileInfo")
    public Result<?> searchItsFileInfo(VeOaYinzhangEntity veOaYinzhangEntity){
        VeFileFilesEntity veFileFilesEntity = veOaYinzhangService.showFileDetailByFileId(veOaYinzhangEntity);
        if (veFileFilesEntity == null){
            return Result.error(500,"无印章的文件信息");
        }
        return Result.OK(veFileFilesEntity);
    }


    //多个导出
    @AutoLog(value = "印章管理-导出excel表格")
    @ApiOperation(value = "导出excel表格", notes = "印章管理-导出excel表格")
    @GetMapping(value = "/exportYinzhang")
    //ModelAndView 导出表格流
    public ModelAndView exportYinzhang(){
        //获取登录人信息
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        VeOaYinzhangEntity veOaYinzhangEntity = new VeOaYinzhangEntity();
        //查全公章
        veOaYinzhangEntity.setYinZhangLeiBie("公共印章");
        List<VeOaYinzhangVo> voList = veOaYinzhangService.export(veOaYinzhangEntity);
        //创建导出流
        ModelAndView modelAndView = new ModelAndView(new JeecgEntityExcelView());
        //文件的文件名
        modelAndView.addObject(NormalExcelConstants.FILE_NAME,"公共印章表");
        //数据的类型
        modelAndView.addObject(NormalExcelConstants.CLASS, VeOaYinzhangVo.class);
        // ExportParams  Export工具类   （参数1--》title:表格标题  参数2--》secomdTitle:第二行的标题，  参数3--》secomdTitle:最下面尾部的信息）
        ExportParams exportParams = new ExportParams("公共印章表","导出人:"+user.getRealname(),"导出公共印章表");
        modelAndView.addObject(NormalExcelConstants.PARAMS,exportParams);
        modelAndView.addObject(NormalExcelConstants.DATA_LIST,voList);

        return modelAndView;
    }



}
